<template>
	<!-- <scroll-view scroll-y class="page-scroll"> -->
	<view scroll-y class="page-scroll">
		<view class="setting-box">
			<view>
				<image src="/static/images/left.png" class="left-icon" @click="backToLast"></image>
			</view>
			<!-- 信息展示 -->
			<view class="top-box">
				<view>
					<image src="/static/images/logo.png" class="avatar-style" alt="avatar"></image>
					<view class="title-style">{{$t("privacySetting")}}</view>
				</view>
			</view>
			<view style="height: 100%;background-color: #fff;">
				<!--权限设置-->
				<view class="card" v-for="(item,index) in rightList" :key="index">
					<view class="card-left">
						<view class="card-title">{{item.rightName}}</view>
						<view class="card-describe">{{item.describe}}</view>
					</view>
					<view class="card-right">
						<button class="setting-btn" v-if="!item.isOpen"
							@click="goSetting(index)">{{$t("settings")}}</button>
						<button class="setting-btn-active" v-else @click="goSetting(index)">{{$t("opened")}}</button>
					</view>
				</view>
			</view>
		</view>
	</view>
	<!-- 弹窗 -->
	<up-popup :show="show3" mode="bottom" @close="close3" @open="open3" :round="10">
		<view>
			<div class="popupBox3">
				<div class="head">
					<span class="head1">{{$t('uppopTitle')}}</span><br>
					<span class="head2">{{$t('uppopSubTitle')}}</span>
				</div>
				<div class="pb3body">
					<div v-for="(item,index) in askRightList" :key="index">
						<div class="bodyItem">
							<div class="bodyItemleft">
								<image :src="item.url" style="width: 55rpx;height: 55rpx;;"></image>
							</div>
							<div class="bodyItemright">
								<span class="bodyItemright1">{{item.rightName}}</span><br>
								<span class="bodyItemright2">{{item.describe}}</span>
							</div>
						</div>
					</div>
					<div class="bodyBtnList">
						<up-button size="large" @click="checkAllPermissions()">{{$t('continue')}}</up-button>
						<!-- show3 = false -->
						<span @click="close3()">{{$t('useLater')}}</span>
					</div>
				</div>
			</div>
		</view>
	</up-popup>
</template>

<script setup lang="ts">
	import { ref, onMounted } from 'vue'
	import { useI18n } from 'vue-i18n'
	import permision from "@/js_sdk/wa-permission/permission.js"
	import { onShow, onHide, onLoad, onUnload } from '@dcloudio/uni-app'; // UniApp 特有的页面钩子

	// #ifdef APP
	const BluetoothAdapter = plus.android.importClass('android.bluetooth.BluetoothAdapter'); // 引入Java 蓝牙类
	// #endif
	onLoad((options : any) => {
		// show3.value = true
		// checkAllPermissions()
	})
	// 页面每次显示时检查所有权限
	onShow(() => {
		askRightList.value = []
		let compat = plus.android.importClass('androidx.core.content.ContextCompat')
		let context = plus.android.runtimeMainActivity()
		// 初始化蓝牙模块 获取蓝牙打开状态 每次更新
		uni.openBluetoothAdapter({
			success(res) {
				// console.log(res)
				rightList.value[1].isOpen = true
			},
			fail: (err) => {
				console.log('搜索失败', err);
				rightList.value[1].isOpen = false
				askRightList.value.push(rightList.value[1])
			}
		})
		
		rightList.value.forEach((item) => {
			if (item.permissionType == 'bluetooth') {
				//空过去
			} else {
				let result = compat.checkSelfPermission(context, item.androidPermissionID)
				console.log("111", item.permissionType, result)
				if (result == 0) {
					item.isOpen = true
				} else {
					askRightList.value.push(item)
				}
			}
		})
		
		if (isAllFinish.value) {
			if (askRightList.value.length > 0) {
				isAllFinish.value = false
				show3.value = true
				console.log("列表11111：",askRightList.value)
			}
		}
	})
	const backToLast = () => {
		uni.navigateBack()
	}
	const show3 = ref(false);
	interface RightList {
		isOpen : boolean,
		rightName : string,
		describe : string,
		permissionType : string, // 新增：权限类型标识
		androidPermissionID ?: string // 新增：Android权限ID
		url ?: string  //icon
		linshi ?: number  //临时拒绝0 -1  1
	}
	const { t } = useI18n()

	function open3() {
		show3.value = true;
	}
	function close3() {
		// checkAllPermissions()
		show3.value = false;
	}
	const rightList = ref<RightList[]>([
		// 
		// {
		// 	isOpen: false,
		// 	rightName: t('accessNotificationPermission'),
		// 	describe: t('describe1'),
		// 	permissionType: 'notification',
		// 	androidPermissionID: 'android.permission.POST_NOTIFICATIONS'
		// },
		{
			isOpen: false,
			rightName: t('accessGeographicLocation'),
			describe: t('describe2'),
			permissionType: 'location',
			androidPermissionID: 'android.permission.ACCESS_FINE_LOCATION',//ACCESS_COARSE_LOCATION粗略位置
			url: "/static/images/dlwztb.png",
			linshi: -2
		},
		// {
		// 	isOpen: false,
		// 	rightName: t('accessWifiPermission'),
		// 	describe: t('describeWifi'),
		// 	permissionType: 'wifi',
		// 	//androidPermissionID: 'android.permission.ACCESS_WIFI_STATE' 
		// 	androidPermissionID: 'android.permission.ACCESS_FINE_LOCATION'  //用于扫描周围的WiFi网络，属于位置权限组
		// },
		{
			isOpen: false,
			rightName: t('accessBluetoothPermissions'),
			describe: t('describe3'),
			permissionType: 'bluetooth',
			androidPermissionID: 'android.permission.BLUETOOTH_CONNECT',
			url: "/static/images/lytb.png",
			linshi: -2
		},
		{
			isOpen: false,
			rightName: t('accessAlbumPermissions'),
			describe: t('describe4'),
			permissionType: 'album',
			androidPermissionID: 'android.permission.READ_EXTERNAL_STORAGE',
			url: "/static/images/album.png",
			linshi: -2
		},
		{
			isOpen: false,
			rightName: t('accessCameraPermissions'),
			describe: t('describeCamera'),
			permissionType: 'camera',
			androidPermissionID: 'android.permission.CAMERA',
			url: "/static/images/camera.png",
			linshi: -2
		}
	])
	const askRightList = ref<RightList[]>([])  //弹窗询问的权限列表
	// 记录每个权限是否已显示过弹窗
	const permissionPromptsShown = ref({
		// notification: false,
		location: false,
		// wifi:false,
		bluetooth: false,
		album: false,
		camera: false
	})
	const isAllFinish = ref(true)  //checkAllPermissions 是否全部运行完 标志位 防止自定义弹窗重复
	// 检查所有权限 
	const checkAllPermissions = async () => {
		show3.value = false
		console.log("222", askRightList.value)
		// rightList
		for (let i = 0; i < askRightList.value.length; i++) {
			const permissionType = askRightList.value[i].permissionType
			// 打开蓝牙模块 单独判断 
			if (permissionType == 'bluetooth') {
				const blueadapter = BluetoothAdapter.getDefaultAdapter();
				if (blueadapter != null) {
					blueadapter.enable();  //打开蓝牙弹窗
					continue; // 继续下一个权限检查
				}
			}
			// 仅当未显示过对应权限弹窗时执行检查
			if (!permissionPromptsShown.value[permissionType]) {
				await checkPermission(i)
				// 标记为已显示
				permissionPromptsShown.value[permissionType] = true
			}
		}
		console.log("isAllFinish", isAllFinish.value)
		// isAllFinish.value = true
		askRightList.value = []
	}
	// 检查单个权限
	const checkPermission = async (index : number) => {
		const platform = uni.getSystemInfoSync().platform
		const item = askRightList.value[index]

		if (!item) return
		let isGranted : boolean
		if (platform === 'ios') {
			isGranted = permision.judgeIosPermission(item.permissionType)
			item.isOpen = isGranted
			// 如果未授权且未显示过弹窗，则显示提示
			if (!isGranted && !permissionPromptsShown.value[item.permissionType]) {
				showIosPermissionPrompt(item.permissionType)
				permissionPromptsShown.value[item.permissionType] = true
			}
		} else {
			try {
				const result = await permision.requestAndroidPermission(item.androidPermissionID)
				isGranted = result === 1
				item.isOpen = result === 1
				item.linshi = result
			} catch (error) {
				console.error('权限检查失败:', error)
			}
		}
	}

	// 设置单个权限（用户主动点击时调用）
	const settingPermission = async (index : number) => {
		const platform = uni.getSystemInfoSync().platform
		const item = rightList.value[index]

		if (platform === 'ios') {
			const isGranted = permision.judgeIosPermission(item.permissionType)
			if (!isGranted) {
				showIosPermissionPrompt(item.permissionType)
			}
		} else {
			try {
				console.log("是否开启", item.isOpen, item.linshi)
				if (item.linshi == 0) {
					const result = await permision.requestAndroidPermission(item.androidPermissionID)
					console.log("result", result)
					item.linshi = result
					handleAndroidPermissionResult2(result, item.permissionType, index)
				} else {
					const result = await permision.requestAndroidPermission(item.androidPermissionID)
					console.log("result", result)
					item.linshi = result
					handleAndroidPermissionResult(result, item.permissionType, index)
				}
			} catch (error) {
				console.error('权限请求失败:', error)
			}
		}
	}

	// iOS 权限弹窗
	const showIosPermissionPrompt = (permissionType : string) => {
		const titles = {
			notification: t('notificationPermission'),
			location: t('locationPermission'),
			bluetooth: t('bluetoothPermission'),
			album: t('albumPermission'),
			camera:t('cameraPermission')
		}

		uni.showModal({
			title: t('need') + `${titles[permissionType]}`,
			content: t('needOpen') + `${titles[permissionType]}` + t('toUse'),
			success: (res) => {
				if (res.confirm) {
					permision.gotoAppPermissionSetting()
				}
			}
		})
	}

	// 处理 Android 权限结果
	const handleAndroidPermissionResult = (result : number, permissionType : string, index : number) => {
		const titles = {
			notification: t('notificationPermission'),
			location: t('locationPermission'),
			bluetooth: t('bluetoothPermission'),
			album: t('albumPermission'),
			camera: t('cameraPermission')
		}
		// 关闭蓝牙
		if (permissionType == 'bluetooth') {
			const blueadapter = BluetoothAdapter.getDefaultAdapter();
			if (blueadapter != null) {
				if (rightList.value[1].isOpen == true) {
					blueadapter.disable();  // 关闭蓝牙弹窗
				} else {
					blueadapter.enable();  // 打开蓝牙弹窗
				}
			}
		}
		else {
			switch (result) {
				case 1: // 已授权
					if (rightList.value[index].isOpen) {
						uni.showModal({
							title: `${titles[permissionType]}` + t('opened'),
							content: t('toClose'),
							confirmText: t('toSetting'),
							cancelText: t('cancel'),      // 从语言包获取取消按钮文本
							success: (res) => {
								if (res.confirm) {
									permision.gotoAppPermissionSetting()
									// 重置标记，允许下次显示弹窗
									permissionPromptsShown.value[permissionType] = false
								}
							}
						})
					} else {
						rightList.value[index].isOpen = true
					}
					break

				case 0: // 拒绝但未勾选"不再询问"
					if (!rightList.value[index].isOpen) {
						// uni.showModal({
						// 	title: t('need') + `${titles[permissionType]}`,
						// 	content: t('manuallyOpen') + `${titles[permissionType]}` + t('toUse'),
						// 	confirmText: t('toSetting'),
						// 	cancelText: t('cancel'),      // 从语言包获取取消按钮文本
						// 	success: (res) => {
						// 		if (res.confirm) {
						// 			permision.gotoAppPermissionSetting()
						// 			// 重置标记，允许下次显示弹窗
						// 			permissionPromptsShown.value[permissionType] = false
						// 		}
						// 	}
						// })
					} else {
						rightList.value[index].isOpen = false
					}
					break

				case -1: // 拒绝并勾选"不再询问"
					if (!rightList.value[index].isOpen) {
						uni.showModal({
							title: t('need') + `${titles[permissionType]}`,
							content: t('manuallyOpen') + `${titles[permissionType]}` + t('toUse'), //请手动开启
							confirmText: t('toSetting'),
							cancelText: t('cancel'),      // 从语言包获取取消按钮文本
							// showCancel: false,
							success: (res) => {
								if (res.confirm) {
									permision.gotoAppPermissionSetting()
									// 重置标记，允许下次显示弹窗
									permissionPromptsShown.value[permissionType] = false
								}
							}
						})
					} else {
						rightList.value[index].isOpen = false
					}
					break
			}
		}

	}
	const handleAndroidPermissionResult2 = (result : number, permissionType : string, index : number) => {
		const titles = {
			notification: t('notificationPermission'),
			location: t('locationPermission'),
			bluetooth: t('bluetoothPermission'),
			album: t('albumPermission'),
			camera: t('cameraPermission')
		}
		// 关闭蓝牙
		if (permissionType == 'bluetooth') {
			const blueadapter = BluetoothAdapter.getDefaultAdapter();
			if (blueadapter != null) {
				if (rightList.value[1].isOpen == true) {
					blueadapter.disable();  // 关闭蓝牙弹窗
				} else {
					blueadapter.enable();  // 打开蓝牙弹窗
				}
			}
		}
		else {
			switch (result) {
				case 1: // 已授权
					if (rightList.value[index].isOpen) {
						uni.showModal({
							title: `${titles[permissionType]}` + t('opened'),
							content: t('toClose'),
							confirmText: t('toSetting'),
							cancelText: t('cancel'),      // 从语言包获取取消按钮文本
							success: (res) => {
								if (res.confirm) {
									permision.gotoAppPermissionSetting()
									// 重置标记，允许下次显示弹窗
									permissionPromptsShown.value[permissionType] = false
								}
							}
						})
					} else {
						rightList.value[index].isOpen = true
					}
					break

				case 0: // 拒绝但未勾选"不再询问"
					if (!rightList.value[index].isOpen) {
						// 无弹窗
					} else {
						rightList.value[index].isOpen = false
					}
					break

				case -1: // 拒绝并勾选"不再询问"
					if (!rightList.value[index].isOpen) {
						// 无弹窗 
					} else {
						rightList.value[index].isOpen = false
					}
					break
			}
		}

	}
	// 导航到设置页面
	function goSetting(index : number) {
		settingPermission(index)
	}
</script>

<style lang="scss" scoped>
	.page-scroll {
		height: 100%;
	}

	.setting-box {
		width: 100%;
		height: 100%;
		/*微信小程序无法使用本地资源图片作为背景图 使用base64格式*/
		background-image: url('');
		background-size: cover;
		background-repeat: no-repeat;
		box-sizing: border-box;
		padding: 2.5rem 0;
		/* #ifdef  MP-WEIXIN*/
		padding-top: 3.5rem;
		/* #endif*/
	}

	.left-icon {
		width: 1.5rem;
		height: 1.5rem;
		margin: -3rem 0 0 0.5rem;
		/* #ifdef  MP-WEIXIN*/
		margin: 0rem 0 0 0.5rem;
		/* #endif*/
	}

	.top-box {
		width: 100%;
		height: 11rem;
		background: linear-gradient(180deg, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 1) 100%);
		position: relative;
		text-align: center;
	}

	.avatar-style {
		width: 8.38rem;
		height: 8.38rem;
		border-radius: 50%;
	}

	.title-style {
		height: 1.5rem;
		line-height: 1.5rem;
		color: rgba(16, 16, 16, 0.8);
		font-size: 0.88rem;
		font-weight: 600;
		text-align: center;
		margin-bottom: 1rem;
	}

	.card {
		margin: 0 auto 1rem;
		width: 92%;
		min-height: 5rem;
		border-radius: 0.94rem;
		background-color: rgba(255, 255, 255, 1);
		color: rgba(16, 16, 16, 1);
		font-size: 0.88rem;
		text-align: center;
		border: 0.06rem solid rgba(187, 187, 187, 1);
		padding: 1rem;
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
	}

	.card-left {
		text-align: left;
		width: 70%;
	}

	.card-title {
		height: 1.25rem;
		line-height: 1.25rem;
		font-weight: 600;
		margin-bottom: 0.3rem;
	}

	.card-describe {
		width: 100%;
		max-height: 3.3rem;
		line-height: 1.1rem;
		color: rgba(154, 154, 154, 1);
		font-size: 0.75rem;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 3;
		-webkit-box-orient: vertical;
	}

	.card-right {
		display: flex;
		align-items: center;
	}

	.setting-btn {
		width: 5rem;
		height: 1.88rem;
		border-radius: 0.25rem;
		background-color: rgba(255, 255, 255, 1);
		color: rgba(16, 16, 16, 1);
		font-size: 0.75rem;
		text-align: center;
	}

	.setting-btn-active {
		width: 5rem;
		height: 1.88rem;
		border-radius: 0.25rem;
		border: none;
		background-color: #DE868F;
		font-size: 0.75rem;
		text-align: center;
		color: #fff;
		font-weight: 600;
	}


	.popupBox3 {
		width: 100%;

		.head {
			width: 100%;
			padding: 30rpx 20rpx;

			.head1 {
				width: 100%;
				font-size: 30rpx;
			}

			.head2 {
				width: 100%;
				font-size: 24rpx;
				color: #9E9E9E;
			}
		}

		.pb3body {
			width: 100%;

			.bodyItem {
				border: 1rpx solid #BBBBBB;
				border-radius: 30rpx;
				margin: 0 20rpx 30rpx;
				display: flex;
				align-items: center;

				.bodyItemleft {
					width: 10%;
					display: inline-block;
					margin-left: 3%;

					image {
						width: 60rpx;
						height: 60rpx;
					}
				}

				.bodyItemright {
					width: 87%;
					display: inline-block;
					margin: 20rpx 0;

					.bodyItemright1 {
						font-size: 30rpx;
						font-weight: bold;
					}

					.bodyItemright2 {
						font-size: 24rpx;
						color: #9E9E9E;
					}
				}
			}

			.bodyBtnList {
				width: 96%;
				margin: 0 auto;
				text-align: center;

				.u-button {
					color: #fff;
					font-weight: 600;
					border-radius: 10px;
					background-color: #de868f;
					border: 1px solid #bbbbbb;
				}

				span {
					height: 2rem;
					font-size: 26rpx;
					line-height: 2rem;
					display: inline-block;
					margin: 0.5rem 0;
					color: #9A9A9A;
				}
			}
		}
	}
</style>